package leetcode_top;

import org.junit.Test;

public class Ex151 {
    class Solution {
        public String reverseWords(String s) {
            if (s == null) return "";
            s = s.replaceAll("\\s+", " "); //将多个空格替换为1个
            s = s.trim(); //保证左右边界是字符
            if (s.length() == 0) return "";
            int start;
            s = " " + s;
            s = s + '#'; //结束符
            String res = "";
            while (s.charAt(0) != '#') {
                if (s.charAt(0) == ' ') {
                    start = 1;
                    while (start < s.length() && s.charAt(start) != ' ' && s.charAt(start) != '#') {
                        start++;
                    }
                    res = s.substring(0, start) + res;
                    //将该部分子串截到后面
                    s = s.substring(start);
                }
            }

            return res.substring(1);
        }
    }

    @Test
    public void test() {
        Solution s = new Solution();
        System.out.println(s.reverseWords("the sky is blue"));
    }
}
